﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MarketPlace.Data.DomainModels;
using MarketPlace.Data;
using MarketPlace.Web.Models;

namespace MarketPlace.Web.Controllers
{
    public partial class NewsController : BaseController
    {
        //
        // GET: /News/

        [OutputCache(Duration = 60, VaryByParam = "None")]
        public ActionResult Index()
        {
            var news1 = db.News.Where(x => x.IsPublished == true).Take(10).OrderByDescending(x => x.Id);

            var news2 = db.News.Where(x => x.IsPublished == true).Take(10).OrderByDescending(x => x.Id);

            var news3 = db.News.Where(x => x.IsPublished == true).Take(10).OrderByDescending(x => x.Id);

            var news4 = db.News.Where(x => x.IsPublished == true).Take(10).OrderByDescending(x => x.Id);

            NewsIndexModel data = new NewsIndexModel
            {
                JobNews = news1.ToList(),

                LocalNews = news2.ToList(),

                TrainingNews = news3.ToList(),

                JobtechNews = news4.ToList()
            };

            return View(data);
        }

        [OutputCache(Duration = 60, VaryByParam = "*")]
        public virtual ActionResult Search([DefaultValue(1)]int page, [DefaultValue(20)]int pagesize, string k)
        {
            k = k.SafeTrim();

            ViewData["k"] = k;

            var qry = db.News.Where(
                x =>

                    (k.IsNullOrEmpty() || x.Title.Contains(k))
                );

            var data = GetPagedList<News>(qry, page, pagesize);

            return View(data);
        }

        [OutputCache(Duration = 60, VaryByParam = "*", VaryByCustom = "login")]
        public virtual ActionResult Details(long id)
        {
            var data = db.Session.Get<SiteDoc>(id);

            return View(data);
        }

        /// <summary>
        /// 阅读排行
        /// </summary>
        /// <param name="during">最近天数</param>
        /// <param name="limit">取多少个</param>
        /// <returns></returns>
        [OutputCache(Duration = 60, VaryByParam = "*")]
        public virtual ActionResult ViewCountList(int during, [DefaultValue(10)]int limit)
        {
            if (limit > 100)
                limit = 100;

            var data = db.News.Where(x => x.CreatedOn >= DateTime.Today.AddDays(-during)).Take(limit).OrderByDescending(x => x.ViewCount).ToList();

            return PartialView(data);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult UpdateViewCount(long id)
        {
            db.Session.CreateSQLQuery("Update SiteDoc Set ViewCount = ViewCount + 1 where Id = " + id).ExecuteUpdate();

            return new EmptyResult();
        }
    }
}
